<?php

class CollectionController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex()
    {      
        $this->render('index');
    }
    public function actionGetPastDueSalesOrderCount(){
        $salesOrderSql = Yii::app()->db->createCommand()->select('count(distinct i.invoice)')
                ->from('tbl_invoice i')
                ->leftJoin('tbl_collection c', 'i.invoice = c.invoice')
                ->where("
                    i.invoicetype = :type
                    and not exists(select * from tbl_rec_led_apply where number = i.invoice) 
                    and exists(select * from tbl_jobs where jobid = i.jobnumber)
                    and not exists(select * from tbl_invoice where salesordersorg = i.invoice)
                    and datediff(now(),i.invoicedate)>=:min and datediff(now(),i.invoicedate)<=:max
                    ");
        $result =array(
            '30'=>0,
            '60'=>0,
            '90'=>0,
            '120'=>0
        );
        foreach($result as $start => $value){
            $min = $start;
            $max = $start+30;
            if($min == 120){
                $max = 99999999;
            }
            $result[$start]=$salesOrderSql->bindValues(array(
                'min'=>$min,
                'type'=>Invoice::TYPE_SALES_ORDERS,
                'max'=>$max
            ))->queryScalar();
        }
        echo json_encode($result);
    }
    public function actionGetPastDueInvoiceCount(){
        $invoiceSql = Yii::app()->db->createCommand()->select('count(distinct i.invoice)')
                ->leftJoin('tbl_rec r', 'r.invoice = i.invoice')
                ->from('tbl_invoice i')
                ->where("i.invoicetype = :type
                    and r.paidoff is null
                    and  datediff(now(),i.invoicedate)>=:min and datediff(now(),i.invoicedate)<=:max");
        $result =array(
            '30'=>0,
            '60'=>0,
            '90'=>0,
            '120'=>0
        );
        foreach($result as $start => $value){
            $min = $start;
            $max = $start+30;
            if($min == 120){
                $max = 99999999;
            }
            $result[$start]=$invoiceSql->bindValues(array(
                'min'=>$min,                
                'max'=>$max,
                'type'=>Invoice::TYPE_INVOICE,
            ))->queryScalar();
        }
        echo json_encode($result);
    }
    public function actionGetSalesOrderList($pastDueDays, $page=null, $sort=null)
    {
        assert('$pastDueDays == 30 || $pastDueDays == 60 || $pastDueDays == 90 || $pastDueDays == 120');
        if ($page > 0)
            $page--;
        $order = '';
        $min =$max=0;
        $min = $pastDueDays;
        $max =$min+30;
        if($pastDueDays == 120){
            $max = 99999999; //unlimited;
        }
        if ($sort != null)
        {
            $orderArr = CJSON::decode($sort);  
            $order = $orderArr[0]['property'] . ' ' . $orderArr[0]['direction'];
        }
        else
        {
            $order = 'i.invoicedate desc,i.custno,i.locno';
        }


        $data = new CActiveDataProvider('Invoice', array(
                    'criteria' => array(
                        'alias' => 'i',
                        'select' => 'distinct i.*',
                        'condition' => "i.invoicetype = '" . Invoice::TYPE_SALES_ORDERS . "'
                    and not exists(select * from tbl_rec_led_apply where number = i.invoice) 
                    and exists(select * from tbl_jobs where jobid = i.jobnumber)
                    and not exists(select * from tbl_invoice where salesordersorg = i.invoice)
                    and datediff(now(),i.invoicedate)>=:min and datediff(now(),i.invoicedate)<=:max
                    ",
                        'params'=>array(
                            'min'=>$min,
                            'max'=>$max
                        ),
                        //'join' => 'join tbl_collection c on i.invoice = c.invoice',
                        'order' => $order,
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));
        $rs['totalCount'] = $data->getTotalItemCount();
        foreach ($data->getData() as $index => $item)
        {
            $rs['data'][$index] = $item->attributes;
            $rs['data'][$index]['amountowned'] = $item->getAmountOwned();
            if ($item->getLastCollection() != null)
            {
                $rs['data'][$index]['lastNotify'] = $item->getLastCollection()->lastNotify;
            }
            else
            {
                $rs['data'][$index]['lastNotify'] = '';
            }
        }
        echo json_encode($rs);
    }

    protected function getInvoiceCrit()
    {
        $crit = new CDbCriteria();
    }

    public function actionGetInvoiceList($pastDueDays, $page=null, $sort=null)
    {
        assert('$pastDueDays == 30 || $pastDueDays == 60 || $pastDueDays == 90 || $pastDueDays == 120');
        $min =$max=0;
        $min = $pastDueDays;
        $max =$min+30;
        if($pastDueDays == 120){
            $max = 99999999; //unlimited;
        }
        if ($page > 0)
            $page--;
        $order = '';

        if ($sort != null)
        {
            $orderArr = CJSON::decode($sort);  
            $order = $orderArr[0]['property'] . ' ' . $orderArr[0]['direction'];
        }
        else
        {
            $order = 'i.invoicedate desc,i.custno,i.locno';
        }


        $data = new CActiveDataProvider('Invoice', array(
                    'criteria' => array(
                        'alias' => 'i',
                        'select' => 'distinct i.*',
                        'join' => '
                          left join tbl_rec r on r.invoice = i.invoice',
                        'condition' => "i.invoicetype = '" . Invoice::TYPE_INVOICE . "'
                    and r.paidoff is null
                    ",
                        'having' => '
                                       datediff(now(),i.invoicedate)>=:min and datediff(now(),i.invoicedate)<=:max',
                        'params'=>array(
                            'min'=>$min,
                            'max'=>$max
                        ),
                        'order' => $order,
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));
        $rs['totalCount'] = $data->getTotalItemCount();
        foreach ($data->getData() as $index => $item)
        {
            $rs['data'][$index] = $item->attributes;
            $rs['data'][$index]['amountowned'] = $item->getAmountOwned();
            if ($item->getLastCollection() != null)
            {
                $rs['data'][$index]['lastNotify'] = $item->getLastCollection()->lastNotify;
            }
            else
            {
                $rs['data'][$index]['lastNotify'] = '';
            }
        }
        echo json_encode($rs);
    }

    public function actionGetContactList($custno, $locno, $page=0, $sort=null)
    {
        if ($page > 0)
        {
            $page--;
        }
        $order = null;
        $crit = new CDbCriteria();
        $crit->addColumnCondition(array(
            'custno' => $custno,
            'locno' => $locno
        ));
        if ($sort != null)
        {
            $order = CJSON::decode($sort);          
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }
        $data = new CActiveDataProvider('Locationcontacts', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));
        $rs = array(
            'totalCount' => $data->getTotalItemCount(),
            'data' => array()
        );
        foreach ($data->getData() as $index => $item)
        {
            $rs['data'][$index] = $item->attributes;
        }
        echo json_encode($rs);
    }
    public function actionGetCollectionList($invoice,$page=0, $sort=null){
        if($page>0) $page--;
        $crit=new CDbCriteria();
        $crit->addColumnCondition(array(
            'invoice'=>$invoice
        ));
        if($sort!=null){
            $order = json_decode($sort);
            $crit->order = $order[0]['property'].' '.$order[0]['direction'];
        }else{
            $crit->order = 'lastNotify desc';
        }
        $data =new CActiveDataProvider('Collection',array(
            'criteria'=>$crit,
            'pagination'=>array(
                'pageSize'=>20,
                'currentPage'=>$page
            )
        ));
        $rs=array(
            'totalCount'=>$data->getTotalItemCount(),
            'data'=>array()
        );
        foreach($data->getData() as $index=>$item){
            $rs['data'][$index] = $item->attributes;
            $rs['data'][$index]['notifyByText'] = Users::getUserNameById($item->notifyBy);
            $rs['data'][$index]['notifyTypeText'] = $item->getNotifyTypeName();
        }
        
        echo json_encode($rs);
    }
  

    public function actionSendNotify($invoice,$notifyType,$notes)
    {
        assert('$notifyType == "email" || $notifyType =="usps" || $notifyType == "phone"');
        $notes= str_replace('%E2%80%8B', '', $notes);
        $collection = new Collection();
        $collection->invoice = $invoice;
        $collection->lastNotify = date('Y-m-d H:i:s');
        $collection->notifyBy = Yii::app()->user->getId();
        switch($notifyType){
            case 'email':
                $collection->notifyType = Collection::NOTIFY_TYPE_EMAIL;
                break;
            case 'phone':
                $collection->notifyType = Collection::NOTIFY_TYPE_PHONE;
                break;
            case 'usps':
                $collection->notifyType = Collection::NOTIFY_TYPE_USPS;
        }
        $collection->notes = $notes;
        if ($collection->save())
        {
            $this->showAjaxMessage('Save successful', true);
        }
        $this->showAjaxMessage($collection->getErrors());
    }

    public function actionGetCollectionDetails($invoice)
    {
        $invoice = Invoice::model()->find('invoice=:invoice', array('invoice' => $invoice));
        if ($invoice != null)
        {
            $collection = $invoice->getLastCollection();
            if ($collection != null)
            {
                $this->renderPartial('_invoiceCollectionDetails', array('collection' => $collection));
            }
        }
    }

}

?>
